<?php
/**
 * Created by PhpStorm.
 * User: lzh 9157374
 * Date: 2018/5/19
 * Time: 下午2:02
 */
namespace Core\common;

class Model
{

    private $db;
    public $table;
    private static $self;
    private $psize = 10;

    /**
     * 表名
     * @param $table
     * @return $this
     */
    protected function table($table,$status)
    {
        if($status){
            $this->table = MOD_ADD . '_'.$table;
        }else{
            $this->table = $table;
        }
 
        $this->db = load()->object('query');
        return $this;
    }

    /**
     * 获取一条记录
     * @param array $aParams [查询条件]
     * @return array               [查询结果]
     * @author Lz
     * @date   2020-05-20
     */
    public function getData($aParams = array(),$uncSt = true)
    {
        if($uncSt){
            $aParams = $this->is_delete($aParams);
        }
        $aParams['field'] = !empty($aParams['field']) ? $aParams['field'] : '*';
        $aParams['where'] = !empty($aParams['where']) ? $aParams['where'] : array();
        $aParams['join'] = !empty($aParams['join']) ? $aParams['join'] : array();


        $query = $this->db->select($aParams['field'])
            ->from($this->table)
            ->where($aParams['where']);

        if($aParams['join'] != []){
            $query = $query->from($this->table, 'a');
            $query = $this->buildJoin($query,$aParams['join']);
        }
        $aResult = $query->get();

        if ($aResult) return $aResult;
        else return FALSE;

    }

    /**
     * 获取多条记录
     * @param array $aParams [查询条件]
     * @return array               [查询结果]
     * @author Lz
     * @date   2020-05-20
     */
    public function top($aParams = array(),$uncSt = true)
    {
        if($uncSt){
            $aParams = $this->is_delete($aParams);
        }
        $aParams['field'] = !empty($aParams['field']) ? $aParams['field'] : '*';
        $aParams['where'] = !empty($aParams['where']) ? $aParams['where'] : array();
        $aParams['order'] = !empty($aParams['order']) ? $aParams['order'] : ['creation_date desc'];
        $aParams['join'] = !empty($aParams['join']) ? $aParams['join'] : array();

        $query = $this->db->select($aParams['field'])
            ->from($this->table)
            ->where($aParams['where']);
        if($aParams['join'] != []){
            $query = $query->from($this->table, 'a');
            
            $query = $this->buildJoin($query,$aParams['join']);
        }
 
        if($aParams['order'] != []){
            $this->orderby($query,$aParams['order']);
        }
        if (isset($aParams['group']) && $aParams['group']) {
            $this->group_by($query,$aParams['group']);
        }
        $aResult = $query->getall();

        if ($aResult) return $aResult;
        else return [];
    }

    /**
     * 获取多条记录列表
     * @param array $aParams [查询条件]
     * @return array               [查询结果]
     * @author Lz
     * @date   2020-05-20
     */
    public function lists($aParams = array(),$uncSt = true)
    {
        if($uncSt){
            $aParams = $this->is_delete($aParams);
        }
        $aParams['field'] = !empty($aParams['field']) ? $aParams['field'] : '*';
        $aParams['where'] = !empty($aParams['where']) ? $aParams['where'] : array();
        $aParams['order'] = !empty($aParams['order']) ? $aParams['order'] : ['creation_date desc'];
        $aParams['limit'] = !empty($aParams['limit']) ? $aParams['limit'] : [0, 999999999];
        $aParams['join'] = !empty($aParams['join']) ? $aParams['join'] : array();

        $query = $this->db->select($aParams['field'])
            ->from($this->table)
            ->where($aParams['where'])
            ->limit($aParams['limit'][0], $aParams['limit'][1]);
        if($aParams['join'] != []){
            $query = $query->from($this->table, 'a');
            $query = $this->buildJoin($query,$aParams['join']);
        }

        if($aParams['order'] != []){
            $this->orderby($query,$aParams['order']);
        }
        if (isset($aParams['group']) && $aParams['group']) {
            $this->group_by($query,$aParams['group']);
        }

        $aResult = $query->getall();
        if ($aResult) return $aResult;
        else return [];
    }
    /**
     * 获取分页列表
     * @param array $aParams [查询条件]
     * @return array               [查询结果]
     * @author Lz
     * @date   2020-05-20
     */
    public function page($aParams = array(),$uncSt = true){
        if($uncSt){
            $aParams = $this->is_delete($aParams);
        }
        $aParams['field'] = !empty($aParams['field']) ? $aParams['field'] : '*';
        $aParams['where'] = !empty($aParams['where']) ? $aParams['where'] : array();
        $aParams['order'] = !empty($aParams['order']) ? $aParams['order'] : ['creation_date desc'];
        $aParams['join'] = !empty($aParams['join']) ? $aParams['join'] : array();
        $aParams['limit'][0] = ($aParams['page'] - 1) * $this->psize;
        $aParams['limit'][1] = $this->psize;
        $aParams['whereor'] = !empty($aParams['whereor']) ? $aParams['whereor'] : array();

        $query = $this->db->select($aParams['field'])
            ->from($this->table)
            ->where($aParams['where'])
            ->limit($aParams['limit'][0], $aParams['limit'][1]);
        if($aParams['whereor'] != []){
            $query = $query->whereor($aParams['whereor']);
        }
        if($aParams['join'] != []){
            $query = $query->from($this->table, 'a');
            $query = $this->buildJoin($query,$aParams['join']);
        }

        if($aParams['order'] != []){
            $this->orderby($query,$aParams['order']);
        }
        if (isset($aParams['group']) && $aParams['group']) {
            $this->group_by($query,$aParams['group']);
        }

        $aResult = $query->getall();

        $total = $this->count($aParams);
        $pager = pagination($total,$aParams['page'], $this->psize);
        $aData = [
            'data'=>$aResult,
            'page'=>$pager,
        ];
        if ($aResult) return $aData;
        else return FALSE;
    }

    /**
     * 添加操作
     * @param array $aParams [查询条件]
     * @return array               [查询结果]
     * @author Lz
     * @date   2020-05-20
     */
    public function add($array = array())
    {

        $aResult = pdo_insert($this->table, $array);

        if ($aResult) return pdo_insertid();
        else return FALSE;

    }

    /**
     * 修改操作
     * @param array $aParams [查询条件]
     * @return array               [查询结果]
     * @author Lz
     * @date   2020-05-20
     */
    public function edit($aData, $aParams = array())
    {
        $aParams = $this->is_delete($aParams);
        $aParams['where'] = !empty($aParams['where']) ? $aParams['where'] : array();
        $aResult = pdo_update($this->table, $aData, $aParams['where']);
        if ($aResult) return $aResult;
        else return FALSE;

    }

    /**
     * 删除操作
     * @param array $aParams [查询条件]
     * @return array               [查询结果]
     * @author Lz
     * @date   2019-04-17
     */
    public function del($aParams = array())
    {
        $aParams = $this->is_delete($aParams);
        $aParams['where'] = !empty($aParams['where']) ? $aParams['where'] : array();
        $aResult = pdo_delete($this->table, $aParams['where']);

        if ($aResult) return $aResult;
        else return FALSE;

    }

    /**
     * 统计数量
     * @param array $aParams [查询条件]
     * @return array               [查询结果]
     * @author Lz
     * @date   2020-05-20
     */
    public function count($aParams = array())
    {
        $aParams['field'] = !empty($aParams['field']) ? $aParams['field'] : '*';
        $aParams['where'] = !empty($aParams['where']) ? $aParams['where'] : array();
        $aParams['order'] = !empty($aParams['order']) ? $aParams['order'] : ['creation_date desc'];
        $aParams['join'] = !empty($aParams['join']) ? $aParams['join'] : array();

        $query = $this->db->select($aParams['field'])
            ->from($this->table)
            ->where($aParams['where']);
        if($aParams['join'] != []){
            $query = $query->from($this->table, 'a');
            $query = $this->buildJoin($query,$aParams['join']);
        }
        if($aParams['order'] != []){
            $this->orderby($query,$aParams['order']);
        }
        if (isset($aParams['group']) && $aParams['group']) {
            $this->group_by($query,$aParams['group']);
        }
        $aResult = $query->getall();

        return count($aResult);
    }

    /**
     * 构造关联条件SQL语句
     *
     *
     * @param $query
     * @param mixed $where 查询条件
     * @return mixed
     */
    public function buildJoin($query,$join)
    {
        if (!is_array($join)) {
            return $query;
        }
        foreach ($join as $field => $val) {
            if ($field && ($val || $val === 0)) {
                foreach($val as $k=>$v){

                    switch ($field) {
                        case 'join':
                            $query->join($v[0], $v[1])->on($v[2],$v[3]);
                            break;
                        case 'leftJoin':
                            $query->leftjoin($v[0],$v[1])->on($v[2],$v[3]);
                            break;
                        case 'rightJoin':
                            $query->rightjoin($v[0],$v[1])->on($v[2],$v[3]);
                            break;
                    }
                }
            }
        }
        return $query;
    }

    public function orderby($query,$order){
        if (!is_array($order)) {
            return $query;
        }
        $count = count($order);
        for ($i=0;$i<$count;){
            $query->orderby($order[$i],$order[$i+1]);
            $i = $i+2;
        }

        return $query;
    }

    public function group_by($query,$group){
        if (!is_array($group)) {
            return $query;
        }
        $count = count($group);
        for ($i=0;$i<$count;$i++){
            $query->groupBy($group[$i]);
        }

        return $query;
    }

    public function is_delete($aParams){
        $table = [
            MOD_ADD . '_'.'auth_group_access',
            MOD_ADD . '_'.'activity',
            MOD_ADD . '_'. 'code',
            MOD_ADD . '_'.'order',
        ];
        if(strpos($this->table,MOD_ADD) !== false){
            $aParams['where']['uniacid'] = uniacid();
            if(!in_array($this->table,$table)){
                $aParams['where']['is_delete'] = 1;
            }
        }
        return $aParams;
    }

    public function __construct()
    {
        $this->table = $this->table?$this->table:MOD_ADD . '_' . basename(str_replace('\\', '/', get_class($this)));
        $this->db = load()->object('query');
    }

    public function __call($name, $arguments)
    {
        $instance = static::getInstance();
        if (method_exists($instance, $name)) {
            return call_user_func_array([$instance, $name], $arguments);
        }
        throw new \Exception('方法:'.$name.'不存在');
    }

    public static function __callStatic($name, $arguments)
    {
        $instance = static::getInstance();

        if (method_exists($instance, $name)) {
            return call_user_func_array([$instance, $name], $arguments);
        }
        throw new \Exception('方法:'.$name.'不存在');
    }
    
    private static function getInstance()
    {
        if (self::$self === null) {
            self::$self = new Model();
        }

        return self::$self;
    }

}